package cn.iocoder.yudao.module.crossborder.platform.job.amazon;

import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.crossborder.platform.dal.dataobject.platformauth.PlatformAuthDO;
import cn.iocoder.yudao.module.crossborder.platform.service.platformauth.PlatformAuthService;
import cn.iocoder.yudao.module.crossborder.platform.service.provider.amazon.AmazonAuthProvider;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * Amazon授权刷新定时任务
 *
 * @author 芋道源码
 */
@Component
@Slf4j
public class AmazonAuthRefreshJob {

    @Resource
    private AmazonAuthProvider amazonAuthProvider;

    @Resource
    private PlatformAuthService platformAuthService;

    @XxlJob("amazonAuthRefreshJob")
    @TenantJob
    public String execute(String param) throws Exception {
        log.info("开始执行Amazon授权刷新定时任务: param={}", param);
        
        try {
            // 1. 获取所有需要刷新的Amazon店铺授权
            LocalDateTime expireThreshold = LocalDateTime.now().plusMinutes(30); // 30分钟内过期的令牌
            List<PlatformAuthDO> expiredAuthList = platformAuthService.getExpiredAuthList(expireThreshold);

            int successCount = 0;
            int totalCount = expiredAuthList.size();

            // 2. 遍历执行令牌刷新
            for (PlatformAuthDO auth : expiredAuthList) {
                if (auth.getAutoRefresh() != null && auth.getAutoRefresh()) {
                    boolean result = amazonAuthProvider.refreshAccessToken(auth.getStoreId());
                    if (result) {
                        successCount++;
                    }
                    log.info("Amazon授权刷新: storeId={}, result={}", auth.getStoreId(), result);
                }
            }

            log.info("Amazon授权刷新完成: 总数={}, 成功={}", totalCount, successCount);
            return String.format("刷新完成: %d/%d", successCount, totalCount);
            
        } catch (Exception e) {
            log.error("Amazon授权刷新失败", e);
            throw e;
        }
    }

}
